import { Effect, Reducer, Subscription } from 'umi';
import { isLogin } from '../utils/common';
import { LOGIN_PAGES_PATHS, clearJump } from '../utils/navigator';

let isFirst = true;

export interface GlobalModelState {
  name: string;
}

export interface GlobalModelType {
  namespace: 'global';
  state: GlobalModelState;
  effects: {
    query: Effect;
  };
  reducers: {
    save: Reducer<GlobalModelState>;
  };
  subscriptions: { setup: Subscription };
}

const GlobalModel: GlobalModelType = {
  namespace: 'global',
  state: {
    name: '全局',
  },
  effects: {
    *query({ payload }, { call, put }) {},
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (isFirst) {
          if (isLogin()) {
            if (LOGIN_PAGES_PATHS.includes(pathname)) {
              clearJump('/');
            }
          } else {
            if (!LOGIN_PAGES_PATHS.includes(pathname) && false) {
              clearJump('/login');
            }
          }
        }
      });
    },
  },
};

export default GlobalModel;
